import React, {useEffect, useState} from 'react';
import {connect} from 'dva'
import {Button, Card, Checkbox, Form, Input, message} from "antd";
import FormRow from "@/custom-components/FormRow";
import {FontColorsOutlined, LockOutlined, UserOutlined} from "@ant-design/icons";
import Cookies from "js-cookie";
import {decrypt, encrypt} from '@/utils/jsencrypt'
import {setExpiresIn, setToken} from "@/utils/auth";

const Login = (
  {
    dispatch,
    loginLoading,
  }) => {

  const [form] = Form.useForm();
  const [uuid, setUuid] = useState('')
  const [codeUrl, setCodeUrl] = useState("")
  const [loginForm, setLoginForm] = useState(
    {
      username: "admin",
      password: "admin123",
      rememberMe: false,
      code: "",
      uuid: ""
    })
  const [captchaOnOff, setCaptchaOnOff] = useState(true) // 验证码开关

  const getCode = () => {
    dispatch({
      type: 'loginR/getCode'
    }).then(res => {
      console.log(res, 'res');
      setCaptchaOnOff(res?.captchaOnOff === undefined ? true : res?.captchaOnOff)
      if (captchaOnOff) {
        setCodeUrl("data:image/gif;base64," + res?.img)
        setLoginForm({
          ...(loginForm),
          uuid: res?.uuid
        })
      }
      setUuid(res?.uuid)
    })
  }

  const getCookie = () => {
    const username = Cookies.get("username");
    const password = Cookies.get("password");
    const rememberMe = Cookies.get('rememberMe')
    setLoginForm({
      ...(loginForm),
      username: username === undefined ? loginForm.username : username,
      password: password === undefined ? loginForm.password : decrypt(password),
      rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
    })
  }

  useEffect(() => {
    getCode()
    getCookie()
    // console.log(loginForm, 'loginForm')
  }, [])

  const login = () => {
    form.validateFields(['username', 'password', 'code']).then(val => {
      // console.log(loginForm, 'loginForm')
      // setLoading(true)
      if (loginForm.rememberMe) {
        Cookies.set("username", loginForm.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.password), { expires: 30 });
        Cookies.set('rememberMe', loginForm.rememberMe, { expires: 30 });
      }else {
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove('rememberMe');
      }
      dispatch({
        type: 'loginR/login',
        payload: {
          ...val,
          uuid: uuid
        }
      }).then(res => {
        if (res) {
          console.log(res, '9999999999')
          message.success('登录成功').then(() => {
          })
          setToken(res?.data?.access_token)
          setExpiresIn(res?.data?.expires_in)
          location.replace('/')
        }else {
          if (captchaOnOff) {
            getCode();
          }
        }
      })
    }).catch(err => {
      console.log(err, 'err')
    })
    // console.log(form.getFieldsValue())
  }

  const rememberMe = (val) => {
    setLoginForm({
      ...(loginForm),
      rememberMe: val.target.checked
    })
  }

  return (
    <div>
      <Card
        title={'登录'}
        hoverable
        style={{
          width: '500px',
          margin: '100px auto 0 auto',
        }}
        bodyStyle={{
          width: "400px",
          margin: '0 auto'
        }}
      >
        <Form
          form={form}
          size={"large"}
        >
          <Form.Item
            name={'username'}
            rules={[{required: true, message: '请输入账号!'}]}
          >
            <Input prefix={<UserOutlined/>} placeholder={'请输入账号'} onPressEnter={login}/>
          </Form.Item>
          <Form.Item
            name={'password'}
            rules={[{required: true, message: '请输入密码!'}]}
          >
            <Input prefix={<LockOutlined/>} type={"password"} placeholder={'请输入密码'} onPressEnter={login}/>
          </Form.Item>
          <FormRow flex={[3, 1]}>
            <Form.Item
              name={'code'}
              rules={[{required: true, message: '请输入验证码!'}]}
            >
              <Input prefix={<FontColorsOutlined/>} placeholder={'请输入验证码'} onPressEnter={login}/>
            </Form.Item>
            {
              codeUrl &&
              <Form.Item>
                <img
                  style={{
                    width: '100%',
                    height: `${document.querySelector('.ant-form-item-control-input-content').offsetHeight.toFixed(2)}px`,
                    margin: 0,
                    padding: 0
                  }}
                  alt={"验证码"}
                  onClick={getCode}
                  src={codeUrl}
                />
              </Form.Item>
            }
          </FormRow>
          <FormRow>
            <Form.Item
              name={'rememberMe'}
              // initialValue={loginForm.rememberMe}
            >
              <Checkbox checked={loginForm.rememberMe} onChange={rememberMe} >记住密码</Checkbox>
            </Form.Item>
          </FormRow>
          <FormRow>
            <Form.Item>
              <Button style={{width: '100%'}} loading={loginLoading} type={"primary"} onClick={login}>登录</Button>
            </Form.Item>
          </FormRow>
        </Form>
      </Card>
    </div>
  );
};

export default connect(({loading}) => ({
  loginLoading: loading.effects['loginR/login'] || false
}))(Login);
